package com.xms.security.api.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.xms.core.config.FinalValueDefaults;
import com.xms.core.model.PagedList;
import com.xms.security.api.model.AddRoleMemberModel;
import com.xms.security.api.model.RemoveRoleMemberModel;
import com.xms.security.entity.RoleMemberShip;
import com.xms.security.entity.RoleMemberShipView;
import com.xms.security.service.role.IRoleMemberShipFinderService;
import com.xms.security.service.role.IRoleMemberShipService;
import com.xms.utils.CollectionUtil;
import com.xms.utils.StringUtil;
import com.xms.utils.UUIDUtil;
import com.xms.web.framework.controller.ApiBaseController;
import com.xms.web.framework.model.JsonResultObject;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.List;
import java.util.UUID;

/**
 * <p>
 * RoleMembersController
 * </p>
 *
 * @author migo
 * @since 2021/10/14
 */
@RestController
@RequestMapping("/{org}/api/security/role/member")
public class RoleMemberShipController extends ApiBaseController {
    private IRoleMemberShipService _roleMemberShipService;
    private IRoleMemberShipFinderService _roleMemberShipFinderService;

    @Autowired
    public RoleMemberShipController(
            IRoleMemberShipService roleMemberShipService,
            IRoleMemberShipFinderService roleMemberShipFinderService) {
        _roleMemberShipService = roleMemberShipService;
        _roleMemberShipFinderService = roleMemberShipFinderService;
    }

    @ApiOperation("获取角色成员列表")
    @GetMapping("list")
    public JsonResultObject list(@RequestParam(value = "roleid", required = true) UUID roleid,
                                 @RequestParam(value = "membername", required = false) String membername,
                                 @RequestParam(value = "typecode", required = false) Integer typecode,
                                 @RequestParam(value = "getall", required = false) Boolean getall,
                                 @RequestParam(value = "page", required = false, defaultValue = "1") Integer page,
                                 @RequestParam(value = "pagesize", required = false, defaultValue = "10") Integer pagesize) throws Exception {
        if (UUIDUtil.isEmpty(roleid)) {
            return JNotSpecifiedParams("roleid");
        }
        LambdaQueryWrapper<RoleMemberShipView> lambdaQueryWrapper = getSortedQueryWrapper("membername", "asc");
        lambdaQueryWrapper.eq(RoleMemberShipView::getRoleid, roleid);
        if (typecode != null) {
            lambdaQueryWrapper.eq(RoleMemberShipView::getTypecode, typecode);
        }
        if (StringUtil.notEmpty(membername)) {
            lambdaQueryWrapper.like(RoleMemberShipView::getMembername, membername);
        }
        if (getall != null && getall) {
            return JOk(_roleMemberShipFinderService.list(lambdaQueryWrapper));
        } else if (page == null || pagesize == null) {
            return JNotSpecifiedParams("page", "pagesize");
        }
        page = (page <= 0 ? 1 : page);
        pagesize = (pagesize <= 0 ? 10 : pagesize);
        IPage<RoleMemberShipView> datas = _roleMemberShipFinderService.page(new Page<>(page, pagesize), lambdaQueryWrapper);
        PagedList<RoleMemberShipView> result = new PagedList<>(datas.getRecords(), page, pagesize, datas.getTotal(), datas.getPages());

        return JOk(result);
    }

    @ApiOperation("添加角色成员")
    @PostMapping("add")
    public JsonResultObject add(@RequestBody AddRoleMemberModel model) {
        if (UUIDUtil.isEmpty(model.roleid) || CollectionUtil.isEmpty(model.memberid)) {
            return JNotSpecifiedParams("roleid", "memberid");
        }

        List<RoleMemberShip> entities = new ArrayList<>();
        for (UUID id : model.memberid) {
            if (UUIDUtil.isEmpty(id))
                continue;
            if (_roleMemberShipService.count(new LambdaQueryWrapper<RoleMemberShip>()
                    .eq(RoleMemberShip::getRoleid, model.roleid)
                    .eq(RoleMemberShip::getMemberid, id)) > 0)
                continue;
            RoleMemberShip entity = new RoleMemberShip();
            entity.setMemberid(id);
            entity.setRoleid(model.roleid);
            entity.setTypecode(model.typecode);
            entity.setRolemembershipid(UUIDUtil.get());
            entities.add(entity);
        }
        if (CollectionUtil.notEmpty(entities)) {
            _roleMemberShipService.saveBatch(entities);
        }
        return JOk();
    }

    @ApiOperation("移除角色成员")
    @PostMapping("removebymemberid")
    public JsonResultObject remove(@RequestBody RemoveRoleMemberModel model) {
        if (UUIDUtil.isEmpty(model.roleid) || CollectionUtil.isEmpty(model.memberid)) {
            return JNotSpecifiedParams("roleid", "memberid");
        }
        //过滤掉管理员
        if (model.roleid.equals(FinalValueDefaults.ADMIN_ROLEID)) {
            model.memberid.removeIf(x -> x.equals(FinalValueDefaults.ADMIN_USERID));
        }
        _roleMemberShipService.remove(new LambdaQueryWrapper<RoleMemberShip>()
                .eq(RoleMemberShip::getRoleid, model.roleid)
                .in(RoleMemberShip::getMemberid, model.memberid));
        return JOk();
    }

    @ApiOperation("移除角色成员")
    @PostMapping("removebyid")
    public JsonResultObject removeById(@RequestBody RemoveRoleMemberModel model) {
        if (UUIDUtil.isEmpty(model.roleid) || CollectionUtil.isEmpty(model.memberid)) {
            return JNotSpecifiedParams("roleid", "memberid");
        }
        //过滤掉管理员
        if (model.roleid.equals(FinalValueDefaults.ADMIN_ROLEID)) {
            model.memberid.removeIf(x -> x.equals(FinalValueDefaults.ADMIN_USERID));
        }
        _roleMemberShipService.remove(new LambdaQueryWrapper<RoleMemberShip>()
                .eq(RoleMemberShip::getRoleid, model.roleid)
                .in(RoleMemberShip::getMemberid, model.memberid));
        return JOk();
    }
}
